package com.linkelee.manage.interceptor;


import com.alibaba.fastjson.JSONObject;
import com.linkelee.api.enums.ReturnCodeEnum;
import com.linkelee.api.result.JsonResult;
import com.linkelee.api.token.TokenHelper;

import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
public class IdentityInterceptor extends HandlerInterceptorAdapter {
    @Autowired
    private TokenHelper tokenHelper;

    public static final String TOKEN_EXCEPTION_NOTIME_MESSAGE = "token失效,请重新登录!";

    public static final String TOKEN_EXCEPTION_NOTOKEN_MESSAGE = "未登录,请重新登录!";

    public static final String TOKEN_CONTENT_TYPE = "application/json";

    public static final String TOKEN_CHARACTER_ENCODING = "utf-8";

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {

        try {

            log.info("---- 请求url:"+request.getRequestURI());

            String token = request.getHeader("token");
            log.info("登录身份验证:" + token);
            // 如果不存在token
            if (Strings.isEmpty(token)) {
                log.info("token nopass--- 未传递token");
                response.setContentType(TOKEN_CONTENT_TYPE);
                response.setCharacterEncoding(TOKEN_CHARACTER_ENCODING);
                response.getWriter().write(JSONObject.toJSONString(JsonResult.builder()
                        .data(null)
                        .code(ReturnCodeEnum.request_notoken.getRequestCode())
                        .msg(TOKEN_EXCEPTION_NOTOKEN_MESSAGE)
                        .build()));
                response.flushBuffer();
                return false;
            }
            // 如果找不到对应token,或者对应的token未生效
            if (!tokenHelper.checkToken(token) || !tokenHelper.checkTokenEnable(token)) {
                log.info("token nopass--- 失效的token");
                response.setContentType(TOKEN_CONTENT_TYPE);
                response.setCharacterEncoding(TOKEN_CHARACTER_ENCODING);
                response.getWriter().write(JSONObject.toJSONString(JsonResult.builder()
                        .data(null)
                        .code(ReturnCodeEnum.request_notoken.getRequestCode())
                        .msg(TOKEN_EXCEPTION_NOTIME_MESSAGE)
                        .build()));
                response.flushBuffer();
                return false;
            }
            log.info("token pass---" + token);
            // 通过,则token续期
            tokenHelper.expireToken(token);
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            log.error("token nopass--- 校验token发生异常" + e.getMessage(), e);
            response.setContentType(TOKEN_CONTENT_TYPE);
            response.setCharacterEncoding(TOKEN_CHARACTER_ENCODING);
            response.getWriter().write(JSONObject.toJSONString(JsonResult.builder()
                    .data(null)
                    .code(ReturnCodeEnum.request_notoken.getRequestCode())
                    .msg(e.getMessage())
                    .build()));
            response.flushBuffer();
            return false;
        }
    }

}
